<template>
  <li
    class="todo-li"
    @mouseenter="mouseHandler(true)"
    @mouseleave="mouseHandler(false)"
    :style="{ backgroundColor: bgColor, color: myColor }"
  >
    <label>
      <input type="checkbox" v-model="isCompleted" />
      <span>{{ todo.title }}</span>
    </label>
    <button class="btn btn-danger" v-show="isShow" @click="delTodo">
      删除
    </button>
  </li>
</template>

<script lang="ts">
import { defineComponent, computed, ref } from "vue";
import { Todo } from "@/types/todo";
export default defineComponent({
  name: "Itrem",
  props: {
    todo: {
      type: Object as () => Todo,
      required: true,
    },
    deleteTodo: {
      type: Function,
      required: true,
    },
    currentIndex: {
      type: Number,
      required: true,
    },
    updateTodo: {
      type: Function,
      required: true,
    },
  },
  setup(props) {
    const bgColor = ref("white"),
      myColor = ref("black"),
      isShow = ref(false);
    const mouseHandler = (flag: boolean) => {
      if (flag) {
        bgColor.value = "pink";
        myColor.value = "green";
        isShow.value = true;
      } else {
        bgColor.value = "white";
        myColor.value = "black";
        isShow.value = false;
      }
    };
    const delTodo = () => {
      if (window.confirm("确定要删除吗？")) {
        props.deleteTodo(props.currentIndex);
      }
    };
    const val = computed(() => {
      return props.todo;
    });
    const isCompleted = computed({
      get() {
        return props.todo.isCompleted;
      },
      set(val) {
        props.updateTodo(props.todo, val);
      },
    });
    return {
      val,
      bgColor,
      myColor,
      isShow,
      mouseHandler,
      delTodo,
      isCompleted,
    };
  },
});
</script>

<style lang="scss" scoped>
.todo-li {
  list-style: none;
  height: 36px;
  line-height: 36px;
  padding: 0 5px;
  border-bottom: 1px solid #ddd;
  label {
    float: left;
    cursor: pointer;
    width: 60%;

    li {
      input {
        vertical-align: middle;
        margin-right: 6px;
        position: relative;
        top: -1px;
      }
    }
  }
  button {
    float: right;
    margin-top: 3px;
  }
  &::before {
    content: initial;
  }
  &::after {
    border-bottom: none;
  }
}
</style>
